<template>
  <div :id="'media-layout-' + item.type" class="media-layout">
    <el-button v-if="isPop" class="btn-close" size="small" @click.stop="onClose">
      <el-icon><i class="jy-icon-layer-closed"></i></el-icon>
    </el-button>
    <div class="media-layout-handle clearfixed">
      <div class="handle-upload flex-end left">
        <file-upload :item="item"></file-upload>
        <span class="handle-upload-tips">{{item.tips}}</span>
      </div>
      <div v-if="!isPop" class="handle-mg flex-end right">
        <div v-if="state.isDisplayIcon">
          <el-button class="clear-ed handle-mg-btn tab-over" type="text" @click.stop="onCancel" >取消</el-button>
          <el-button class="clear-ed handle-mg-btn tab-over" type="text" @click.stop="onDelete" v-if="state.isDisplayIcon">删除</el-button>
        </div>
        <el-button class="clear-ed handle-mg-btn tab-over" type="text" @click.stop="onManage" v-else>管理</el-button>
      </div>
      <div v-if="!isPop" class="handle-mg flex-end right margin-top-bottom-10 clear">
        <el-button type="primary" size="small" @click="onLoadCurrentSiteId">加载当前站点图片</el-button>
        <el-popover
          placement="right"
          trigger="click">
          <el-input v-model="state.loadSiteId"></el-input>
          <template #reference>
            <el-button type="primary" size="small" @click="onLoadBySiteId">加载指定站点图片</el-button>
          </template>
        </el-popover>
        <el-button type="success" size="small" @click="onLoadAllImgs">加载所有图片</el-button>
      </div>
    </div>

    <div class="media-layout-group">
      <div v-if="mediaData" class="infinite-list-wrapper">
        <ul class="group-lists" v-infinite-scroll="onLoad">
          <li
            v-for="(item_, index) in mediaData.list"
            :key="item_.id + '-' + index">
            <div class="group-item" @click.stop="onAddComponent($event, item_, index)">
              <div v-if="item_.loading" v-loading="item_.loading" class="group-item-con"></div>
              <div v-else class="group-item-con">
                <div v-if="item.type==MEDIAS.image.type" class="popover-img-con">
                  <img v-lazy="item_.url" @click="onConsoleUrl(item_.url)">
                  <el-popover
                    placement="right"
                    :width="state_.previewImgHei"
                    trigger="hover">
                    <img v-lazy="item_.url" class="popover-img">
                    <el-input v-model="item_.name"></el-input>
                    <el-input v-model="item_.url"></el-input>
                    <template #reference>
                      <el-button size="small">
                        <el-icon><i class="jy-icon-view"></i></el-icon>
                      </el-button>
                    </template>
                  </el-popover>
                </div>
                <div v-else-if="item.type==MEDIAS.video.type" class="popover-img-con">
                  <p class="width-height-100 clear-ed">
                    <i class="jy-icon-video1"></i>
                  </p>
                  <el-popover
                    placement="right"
                    :width="state_.previewImgHei"
                    trigger="hover">
                    <el-input v-model="item_.name"></el-input>
                    <el-input v-model="item_.url"></el-input>
                    <template #reference>
                      <el-button size="small">
                        <el-icon><i class="jy-icon-view"></i></el-icon>
                      </el-button>
                    </template>
                  </el-popover>
                </div>
                <div v-else class="clear-ed popover-img-con">
                  <p class="width-height-100 clear-ed">
                    <i class="jy-icon-music"></i>
                  </p>
                  <el-popover
                    placement="right"
                    :width="state_.previewImgHei"
                    trigger="hover">
                    <el-input v-model="item_.name"></el-input>
                    <el-input v-model="item_.url"></el-input>
                    <template #reference>
                      <el-button class="font-12" size="small">
                        <el-icon><i class="jy-icon-view"></i></el-icon>
                      </el-button>
                    </template>
                  </el-popover>
                </div>
                <div :class="{active:item_.isDelete, 'delete-icon': true}" v-if="state.isDisplayIcon"></div>
              </div>
            </div>
            <span :title="item_.name" class="group-item-name txt_nowrap txt_ellipsis">{{item_.name}}</span>
          </li>
        </ul>
        <p v-if="state.loading" class="text-center font-12 color-white">加载中...</p>
        <p v-if="noMore" class="text-center font-12 color-white">没有更多了</p>
      </div>
    </div>
    <div v-if="isPop" :class="{'triangle-border-right': isPop }"></div>
  </div>
</template>

<script setup lang="ts">
import FileUpload from '@/views/components/file-upload.vue'
import { MEDIAS } from '@/const/web/'
import { MOBILE_WID_HEI, COMPONENT_TYPES } from '@/const/'
import { useWebMediaStore } from '@/store/web/media'
import { useWebPageStore } from '@/store/web/page'
import { useWebSiteStore } from '@/store/web/site'
import { useWebComponentStore } from '@/store/web/component'
import { useWebControlsStore } from '@/store/web/controls'
import { ComponentTypesDefaultDom } from '@/store/models/component-default-data'

const props = defineProps<{ 
  item: IWebMediaItem,
  isPop: boolean,
}>()

const useWebMedia = useWebMediaStore()
const useWebPage = useWebPageStore()
const useWebSite = useWebSiteStore()
const useWebControls = useWebControlsStore()
const useWebComponent = useWebComponentStore()
const state = reactive({
  isDisplayIcon: false,
  loading: false,
  loadSiteId: -1,
})
const state_ = {
  tabGroup: 0,
  previewImgHei: 400,
  isResetList: false,
}

const noMore = computed(() => {
  const mediaData = useWebMedia.mediaAllData[props.item.type]
  return mediaData.list.length >= mediaData.total
})
const mediaData = computed(() => {
  return useWebMedia.mediaAllData[props.item.type]
})
const disabled = computed(() => {
  return state.loading || noMore.value
})
const onConsoleUrl = () => {
  // console.log(url + ',');
}
const onClose = () => {
  useWebMedia.hiddenMediaPop()
}
const onManage = () => {
  state.isDisplayIcon = true
}
const onDelete = () => {
  const items: string[] = []
  const mediaData = useWebMedia.mediaAllData[props.item.type]
  mediaData.list.forEach((item: IWebMediaItem) => {
    if(item.isDelete) {
      items.push(item.id)
    }
  })
  useWebMedia.deleteMediaList({ type: props.item.type, items })
}
const onCancel = () => {
  state.isDisplayIcon = false
}
const onLoadCurrentSiteId = () => {
  state.loadSiteId = Number(useWebSite.id)
  state_.isResetList = true
  onLoad()
}
const onLoadBySiteId = () => {
  state_.isResetList = true
  onLoad()
}
const onLoadAllImgs = () => {
  state.loadSiteId = 0
  onLoad()
}
const onLoad = () => {
  if(state.loadSiteId == -1) {
    return
  }
  state.loading = true
  const mediaData = useWebMedia.mediaAllData[props.item.type]
  let nextPage = 1
  let pageSize = 20
  if(mediaData) {
    nextPage = mediaData.page + 1
    pageSize = mediaData.pageSize
  }
  if(state_.isResetList) {
    nextPage = 1
  }
  const cb = () => {
    // 数据全部加载完成
    state.loading = false
  }
  if(mediaData && nextPage <= mediaData.totalPage) {
    if(state.loadSiteId && _.parseInt(state.loadSiteId) > 0) {
      useWebMedia.getMediaData({ page: nextPage, pageSize, type: props.item.type, site_id: state.loadSiteId, isResetList: state_.isResetList, cb})
    } else {
      useWebMedia.getMediaData({ page: nextPage, pageSize, type: props.item.type, isResetList: state_.isResetList, cb})
    }
    state_.isResetList = false
  }
}
const onAddImg = (e: any, item: IWebMediaItem) => {
  const target = e.target
  const url = item.url
  const ratio = getImgRatio(target.naturalWidth, target.naturalHeight)
  const width = _.parseInt(target.naturalWidth * ratio)
  const height = _.parseInt(target.naturalHeight * ratio)
  const componentData = _.cloneDeep(ComponentTypesDefaultDom[COMPONENT_TYPES.wb_img])
  const imgData = { commonAttr: { url }, conAttr: { width, height } }
  _.merge(componentData, imgData)
  useWebPage.addComponent(componentData)
}
const onAddAudio = (e: any, item: IWebMediaItem) => {
  const url = item.url
  const audioData = { commonAttr: { url }, conAttr: { width: 68, height: 68 } }
  const componentData = _.cloneDeep(ComponentTypesDefaultDom[COMPONENT_TYPES.wb_audio])
   _.merge(componentData, audioData)
  useWebPage.addComponent(componentData)
}
const onAddVideo = (e: any, item: IWebMediaItem) => {
  const poster = item.poster ? item.poster : ''
  const url = item.url
  const width = MOBILE_WID_HEI.width
  const height = _.parseInt(width/16 * 9)
  const componentData = _.cloneDeep(ComponentTypesDefaultDom[COMPONENT_TYPES.wb_video])
  const videoData = { commonAttr: { url, poster }, conAttr: { width, height } }
   _.merge(componentData, videoData)
  useWebPage.addComponent(componentData)
}
const onAddComponent = (e: any, item: IWebMediaItem, index: number) => {
  const url = item.url
  const mediaPop = useWebMedia.mediaPop
  const componentData = useWebComponent.currentComponentData
  if(props.isPop) {
    if(!componentData) {
      let attrs = { bgUrl: url }
      if(useWebPage.isSite) {
        useWebSite.updateSiteAttrs(attrs)
      } else {
        useWebPage.updatePageAttrs({attrs})
      }
    } else {
      const comAttr = mediaPop.comAttr
      const picAttr = mediaPop.picAttr
      const index = mediaPop.index
      const qIndex = mediaPop.qIndex
      if(index >= 0) {
        const isInteractionData = mediaPop.isInteractionData
        const data_: any = { item: {}, index }
        data_.item[picAttr] = url
        if(isInteractionData) {
          const interactionData = _.cloneDeep(componentData.interactionData)
          if(interactionData.isDimension) {
            interactionData[comAttr][index][qIndex][picAttr] = url
          } else {
            interactionData[comAttr][index][picAttr] = url
          }
          useWebComponent.updateInteractionData(interactionData)
        } else if (mediaPop.event && mediaPop.event.controlId) {
          data_.controlId = mediaPop.event.controlId
          useWebControls.updateWbComponentItem(data_)
        } else {
          if(qIndex >= 0) {
            delete data_.item[picAttr]
            data_.item[comAttr] = []
            data_.item[comAttr][qIndex] = {}
            data_.item[comAttr][qIndex][picAttr] = url
            useWebComponent.updateComponentItem(data_)
          } else {
            useWebComponent.updateComponentItem(data_)
          }
        }
      } else {
        const isHaveCom = comAttr && comAttr.length > 0
        const params: any = {}
        if(isHaveCom) {
          let comAttrs = comAttr.split(".")
          if(comAttrs.length > 1) {
            const comAttr_ = comAttrs.shift()
            //@ts-ignore
            recursionAssignment(comAttrs.join('.'), params[comAttr_] = {}, picAttr, url)
          } else {
            params[comAttr] = {}
            params[comAttr][picAttr] = url
          }
        } else {
          params[picAttr] = url
        }
        useWebComponent.updateCurrentComponentData(params)
      }
    }
  } else {
    if(state.isDisplayIcon) {
      e.stopPropagation()
      e.preventDefault()
      useWebMedia.updateMediaItem({ type: props.item.type, index, item: { isDelete:!item.isDelete }})
      return
    }
    if(props.item.type == MEDIAS.image.type) {
      onAddImg(e, item)
    }else if(props.item.type == MEDIAS.audio.type) {
      onAddAudio(e, item)
    }else if(props.item.type == MEDIAS.video.type) {
      onAddVideo(e, item)
    }
  }
}
const getImgRatio = (imgW: number, imgH: number, scale = 1) => {
  var w = imgW,
    h = imgH;
  var iw = imgW/scale,
    ih = imgH/scale;
  var xRatio = iw / w,
    yRatio = ih / h,
    sRatio = 1;
  sRatio = Math.min(xRatio, yRatio)
  return sRatio
}
const recursionAssignment = (comAttr: string, params: any, picAttr: any, url: string) => {
  let comAttrs = comAttr.split(".")
  if(comAttrs.length > 1) {
    let comAttr_ = comAttrs.shift()
    //@ts-ignore
    recursionAssignment(comAttrs.join('.'), params[comAttr_] = {}, picAttr, url)
  } else {
    params[comAttr] = {}
    params[comAttr][picAttr] = url
  }
}

const initComp = () => {}
initComp()

</script>

<style lang="scss">
  @import '@/assets/scss/common.scss';
  .el-radio-button__orig-radio:checked+.el-radio-button__inner {
      color: #fff;
      background-color: var(--btn-blue);
      border-color: var(--btn-blue);
      -webkit-box-shadow: -1px 0 0 0 var(--btn-blue);
      box-shadow: -1px 0 0 0 var(--btn-blue);
      font-weight: normal;
  }
  .popover-img{
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  .width-height-100{
    width: 100%;
    height: 100%;
  }
  .media-layout{
    max-width: 760px;

    .el-pagination.is-background .el-pager li{
      height: 24px;
      line-height: 24px;
      margin: 0 3px;
      min-width: 24px;
    }

    .btn-upload{
      color: #fff;
      background-color: var(--btn-blue);
      border-color: var(--btn-blue);
      padding: 8px 26px;
      border-radius: 4px;
    }

    .el-button--primary {
      color: #fff;
      background-color: var(--btn-blue);
      border-color: var(--btn-blue);
    }
    .el-radio-button__inner{
      font-weight: normal;
      font-size: 16px;
    }
    .el-menu-item-group__title{
      padding: 7px 7px !important;
      text-align: center;
      margin-bottom: 12px;
      color: #43475C !important;
    }

    .clear-ed i{
      font-size: 24px;
    }
    .clear-ed .font-12 i{
      font-size: 12px;
    }
    .el-tabs__header{
      margin: 0;
    }
    .btn-close{
      position: absolute;
      right: 10px;
      top: 10px;
      border: none;
    }

    .media-layout-handle{
      .left{
        float: left;
      }

      .right{
        float: right;
      }

      .handle-upload{

        .handle-upload-btn{
          font-size: 14px;
          color: #fff;
          width: 118px;
          height: 30px;
          // line-height: 30px;
          text-align: center;
          background: #127BFF;
        }
        .handle-upload-btn:active{
          color: #eee;
          font-size: 13px;
        }

        .handle-upload-tips{
          font-size: 12px;
          color: #A5AFBE;
          margin-left: 12px;
        }
      }

      .handle-mg{
        height: 38px;

        .handle-mg-btn{
          font-size: 12px;
          color: #43475C;
          margin-left: 20px;
        }
      }
    }

    .media-layout-group{
      .group-tabs{
        display: flex;

        a{
          position: relative;
          // width: 68px;
          height: 16px;
          margin: 0px;
          font-size: 12px;
          color: #43475C;
          padding: 0 10px;
          border-right: 1px solid #dcdfe6;
          border-radius: 0;
          text-decoration: none;

          span{
            display: block;
            margin-top: -2px;
            padding: 0 12px;
            line-height: 20px;
            text-align: center;
            border-radius: 2px;
          }
        }
        a:first-child{
          padding-left: 0px;
        }
        a:last-child{
          border-right: none;
        }
      }

      .group-lists{
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
        padding-top: 18px;
        overflow: auto;
        max-height: 362px;

        div, li{
          width: 98px;
          margin: 0 4px 8px 0;
          padding: 0;
          cursor: pointer;
          flex-direction: column;

          .group-item{
            width: 90px;
            height: 90px;
            background: #F3F5FA;
            position: relative;
            .group-item-con{
              width: inherit;
              height: inherit;
            }
            .el-loading-parent--relative{
              position: static;
            }

            .delete-icon{
              position: absolute;
              top: 4px;
              left: 4px;
              background-image: url('//static.hd.xxx.com/jye/fe-web/images/btn-media-unselect.png');
              width: 13px;
              height: 13px;
              background-size: contain;


              &.active{
                background-image: url('//static.hd.xxx.com/jye/fe-web/images/btn-media-select.png');
              }
            }


            p{
              text-align: center;
              font-size: 24px;
              line-height: 90px;
            }
            img{
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
            .popover-img-con{
              position: relative;
              width: inherit;
              height: inherit;

              .el-button{
                border: none;
                background-color: transparent;
                color: #fff;
              }
            }
            .popover-img-con span{
              position: absolute;
              bottom: 0;
              right: 0;
              object-fit: contain;
              line-height: 20px;
            }
          }
          .group-item-name{
            display: block;
            width: 100%;
            font-size: 11px;
            color: #43475C;
            letter-spacing: 0;
            -webkit-line-clamp: 1;
            text-align: center;
          }
        }
        li:hover{
          .group-item-name{
            color: #66b1ff;
          }
        }
      }

      .is-group{
        span{
          color: #fff !important;
          background: #127BFF;
        }
      }
    }

    .flex-end{
      display: flex;
      align-items: flex-end;
    }

    .popper__arrow {
      border-width: 6px;
      filter: drop-shadow(0 2px 12px rgba(0,0,0,.03));
    }
    .popper__arrow:after {
        bottom: -6px;
        left: 1px;
        border-right-color: #fff;
        border-left-width: 0;
    }

    .popper__arrow:after {
        content: " ";
        border-width: 6px;
    }
    .popper__arrow, .popper__arrow:after {
      position: absolute;
      display: block;
      width: 0;
      height: 0;
      border-color: transparent;
      border-style: solid;
      bottom: -6px;
      left: 1px;
      border-right-color: #fff;
      border-left-width: 0;
    }

  }
</style>
